package com.bestcem.xm.user.grpc.client;

import com.bestcem.bp.pay.grpc.v1.common.CreateResponse;
import com.bestcem.bp.pay.grpc.v1.services.CreatePlatformWalletRequest;
import com.bestcem.bp.pay.grpc.v1.services.CreateWalletArgs;
import com.bestcem.bp.pay.grpc.v1.services.WalletServiceGrpc;
import com.bestcem.xm.common.core.constant.GrpcClientNames;
import com.bestcem.xm.common.core.sign.grpc.core.GrpcTemplate;
import com.bestcem.xm.user.service.dto.user.OrganizationDTO;
import com.zy.dp.proto.base.v1.Code;
import lombok.extern.slf4j.Slf4j;
import net.devh.boot.grpc.client.inject.GrpcClient;
import org.springframework.stereotype.Service;

import javax.annotation.Nullable;
import javax.annotation.Resource;

/**
 * 企业钱包相关grpc接口
 *
 * @author qiongyu.cui <qiongyu.cui@idiaoyan.com>
 * @version v1.0
 * @date 2022/3/18 15:50
 */
@Slf4j
@Service(value = "userWalletGrpcService")
public class UserWalletGrpcService {

    @GrpcClient(GrpcClientNames.PAY)
    private WalletServiceGrpc.WalletServiceBlockingStub stub;

    @Resource
    private GrpcTemplate grpcTemplate;

    /**
     * 创建平台钱包
     *
     * @param platformCode
     * @param name
     * @param org
     * @return WalletRechargeInfoDTO
     * @author wangyunyun <yunyun.wang@idiaoyan.com>
     * @date 2022/7/16 21:14
     */
    @Nullable
    public String createPlatformWallet(String platformCode, String name, OrganizationDTO org) {
        // 设置参数
        CreatePlatformWalletRequest.Builder builder = CreatePlatformWalletRequest.newBuilder();
        if (platformCode != null) {
            builder.setPlatformCode(platformCode);
        }
        CreatePlatformWalletRequest request = builder
                .setWalletArgs(this.buildCreateWalletArgs(name, org))
                .build();
        // 加签并请求
        grpcTemplate.addSign(request, GrpcTemplate.SEVER_CODE_PAY);
        CreateResponse response = null;
        try {
            response = stub.createPlatformWallet(request);
        } catch (Exception e) {
            log.error("创建平台钱包请求失败", e);
            return null;
        }
        // 返回值处理
        if (response != null && Code.OK_VALUE == response.getStatus().getCodeValue()) {
            return response.getId();
        } else {
            log.error("创建平台钱包请求失败, response:{}", response != null ? response.toString() : null);
            return null;
        }
    }

    private CreateWalletArgs buildCreateWalletArgs(String name, OrganizationDTO org) {
        CreateWalletArgs.Builder walletArgs = CreateWalletArgs.newBuilder();
        walletArgs.setOrgId(org.getOrgId());
        if (name != null) {
            walletArgs.setName(name);
        }
        if (org.getOrgId() != null) {
            walletArgs.setOrgId(org.getOrgId());
        }
        if (org.getCode() != null) {
            walletArgs.setOrgCode(org.getCode());
        }
        if (org.getName() != null) {
            walletArgs.setOrgName(org.getName());
        }
        return walletArgs.build();
    }

}
